package com.jiangnan.ui.activity

import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.jiangnan.R
import com.jiangnan.databinding.ActivityItemAdapterRepositoryBinding
import com.jiangnan.entity.Book
import com.jiangnan.util.CurrentHolder
import com.jiangnan.util.CurrentLoginInfo
import com.jiangnan.util.GlideUtil
import com.jiangnan.util.NavigationUtil
import com.jiangnan.util.SharedPrefUtil
import com.jiangnan.util.ToastUtil
import com.jiangnan.viewmodel.AuthViewModel
import com.jiangnan.viewmodel.InteractionViewModel
import com.jiangnan.viewmodel.RecommendationViewModel

class ItemAdapterRepositoryActivity : BaseActivity() {

    private lateinit var binding: ActivityItemAdapterRepositoryBinding
    private lateinit var viewModel: com.jiangnan.viewmodel.BookViewModel
    private lateinit var recommendationViewModel: RecommendationViewModel
    private lateinit var interactionViewModel: InteractionViewModel
    private lateinit var authViewModel: AuthViewModel

    private val TAG = "ItemAdapterRepositoryActivity"

    // 假设当前登录用户ID，实际情况可从登录状态中获取
    private var currentUserId: Long? = null

    private var currentBook: Book? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        binding = DataBindingUtil.setContentView(this, R.layout.activity_item_adapter_repository)
        binding.lifecycleOwner = this

        viewModel = ViewModelProvider(this).get(com.jiangnan.viewmodel.BookViewModel::class.java)
        recommendationViewModel = ViewModelProvider(this).get(RecommendationViewModel::class.java)
        interactionViewModel = ViewModelProvider(this).get(InteractionViewModel::class.java)
        authViewModel = ViewModelProvider(this).get(AuthViewModel::class.java)
//        currentUserId = CurrentLoginInfo.getCurrentLoginInfo()!!.id.toLong()
        SharedPrefUtil.getLoginInfo(this).let {
            currentUserId = it!!.id.toLong()
        }

        initView()
        initObserveResult()
        initListeners()


    }

    private fun initView() {

        // 接收 Book 对象
        val book = intent.getParcelableExtra<Book>("book")
        currentBook = book
        book?.let {
            GlideUtil.loadImageWithPlaceholder(
                this,
                it.img ?: "",
                R.drawable.img_default,
                R.drawable.img_error,
                binding.ivBookImg
            )
            binding.tvBookTitle.text = it.title
            binding.tvBookTitle.isSelected = true
            binding.tvBookAuthor.text = it.author
            binding.tvBookIsbn.text = "ISBN " + it.isbn
            binding.tvBookPrice.text = "价格 ￥" + it.price + "元"
            binding.tvBookLastNum.text = "余量 " + it.lastNum + "/" + it.sum + "本"
            binding.tvBookDetail.text = it.summary
        }

        recommendationViewModel.getRating(currentUserId!!.toInt(), book?.id!!)
    }

    private fun initListeners() {

        // 假设借阅按钮 ID 为 btnBorrow，在布局中已设置该按钮
        binding.btnBorrow.setOnClickListener {
            currentBook?.let { book ->
                // 检查库存
                if (book.lastNum!!.toInt() <= 0) {
                    ToastUtil.showShort(this, "库存不足，无法借阅")
                    return@setOnClickListener
                }
                // 发起借阅请求
                book.id?.let { it1 -> viewModel.borrowBook(currentUserId!!, it1) }
            }
        }
        binding.btnFavorite.setOnClickListener {
            interactionViewModel.markFavorite(currentUserId!!.toInt(), currentBook?.id!!)
        }

        binding.btnRating.setOnClickListener {
            interactionViewModel.updateRating(currentUserId!!.toInt(), currentBook?.id!!, binding.ratingBar.rating.toDouble())
        }
    }

    /**
     * 观察借阅接口返回结果
     */
    private fun initObserveResult() {

        viewModel.borrowResponse.observe(this) { res ->
            res?.let {
                if (it.code == 1) {
                    // 将借阅次数 + 1
                    interactionViewModel.borrowBook(currentUserId!!.toInt(), currentBook?.id!!)
                    // 借阅成功，更新 UI 显示剩余库存减一
                    currentBook?.let { book ->
                        // 假设后端已更新库存，此处也更新本地对象显示
                        val currentNum = book.lastNum?.toIntOrNull() ?: 0
                        book.lastNum = if (currentNum - 1 < 0) "0" else (currentNum - 1).toString()

                        binding.tvBookLastNum.text = "余量 " + book.lastNum + "/" + book.sum + "本"
                    }
                    ToastUtil.showShort(this, "借阅成功")
                } else {
                    ToastUtil.showShort(this, it.msg)
                }
            }
        }

        recommendationViewModel.rating.observe(this) { res ->
            binding.ratingBar.rating = res.data?.toFloat()?: 0f
        }

        recommendationViewModel.toastMessage.observe(this) {
            ToastUtil.showShort(this, it)
        }

        interactionViewModel.toastMessage.observe(this) {
            ToastUtil.showShort(this, it)
        }
    }
}
